﻿<?php 	
class zidong{
	private $automatic_config;
	private $mysql_host='127.0.0.1';
	private $mysql_user='root';
	private $mysql_pwd='root';
	private $mysql_db='cyzx';
	private $mysql_prefix = 'clam_';
	
	private $leavel_type;
	private $leavel;
	private $currency;
	function __construct(){
		set_time_limit(0); 
		date_default_timezone_set('PRC'); 
		$this->initLeavel();
		$this->initLeavelRatio();
		$this->initCurrency();
		
	}
	private  function  initLeavelRatio()
	{
	    $sql="select * from ".$this->mysql_prefix."leavel_ratio";
	    $ratio=$this->lianKuArray($sql);
	    $ratios=[];
	    foreach ($ratio as $v){
	        if (isset($this->leavel[$v['leavel_id']]) ){
	            $ratios[$v['leavel_id']][$v['reward_type']]=$v;
	        }
	    }
	    $this->leavel_type=$ratios;
	}
	private  function  initCurrency()
	{
	    $sql="select * from ".$this->mysql_prefix."currency";
	    $ratio=$this->lianKuArray($sql);
	    $ratios=[];
	    foreach ($ratio as $v){
	            $ratios[$v['id']]=$v;
	    }
	    $this->currency=$ratios;
	}
	private  function  initLeavel()
	{
	    $sql="select * from ".$this->mysql_prefix."leavel where status=1";
	    $ratio=$this->lianKuArray($sql);
	    $ratios=[];
	    foreach ($ratio as $v){
	        $ratios[$v['id']]=$v;
	    }
	    $this->leavel=$ratios;
	}
	//==============================================================================#
	//====================================自动程序入口==============================#
	public function jingtai(){
	    $type=2;
	    $power_money=$this->getJingtaiPowerMoney();
	    if (!$power_money) {
	        return ;
	    }
	    foreach ($power_money as $money_info)
	    {
	        $user=$this->getUserByUserId($money_info['user_id']);
	        if (!$user) {
	            continue;
	        }
	        if ($user['lock']) {
	            continue;
	        }
	        $tui_user=$this->getBeTuiUserByUser($user['id']);
	        if ($tui_user) {
	            $this->decMemberMoneyByMemberIdAndMoneyId($user['id'], $money_info['currency_id'], $money_info['num']);
	            continue;
	        }
	        if(!isset($this->leavel[$user['leavel']]))
	        {
	            continue;
	        }
	        $add_num=$this->leavel[$user['leavel']]['money']*$this->leavel_type[$user['leavel']][$type]['ratio'];
	        $add_num=min($add_num,$money_info['num']);
	        if ($add_num>0) {
	           $this->addRewardMoney($user['id'],$add_num,$type);
	            $this->decMemberMoneyByMemberIdAndMoneyId($user['id'], $money_info['currency_id'], $add_num);
	        }
	        
	    }
		
	}
	public function duipeng()
	{
	    $user_all=$this->getDuipengPowerUser();
	    $type=3;
	    if(!$user_all)
	    {
	        return ;
	    }
	    foreach ($user_all as $user)
	    {
	        if ($user['lock']) {
	            continue;
	        }
	        $yeji=min($user['yeji1'],$user['yeji2']);
	        $add_num=$yeji*$this->leavel_type[$user['leavel']][$type]['ratio'];
	        $log=$this->getBonusLogByUserId($user['id']);
	        if ($log) {
	            $add_num=min($this->leavel[$user['leavel']]['day_max_reward']-$log['bonus6'],$add_num);
	        }
	        if ($add_num>0) {
	           $this->addRewardMoney($user['id'],$add_num,$type);
	        }
	        $sql="update ".$this->mysql_prefix."user  set yeji1=yeji1-".$yeji.",yeji2=yeji2-".$yeji." where id=".$user['id'];
	        $this->sqlCarry($sql);
	        
	    }
	    
	}
	
	private function getBonusLogByUserId($user_id)
	{
	    $sql="select * from ".$this->mysql_prefix."bonus_log where add_time=".strtotime(date('Y-m-d')).' and user_id='.$user_id;
	    $log=$this->lianKu($sql);
	    return $log;
	    
	}
	private function getDuipengPowerUser(){
// 	    $suffix=$this->checkSuffix();
	    $suffix='';
	    $money_id=5;
	    $sql="select * from ".$this->mysql_prefix."user".$suffix." where yeji1>0 and yeji2>0";
	    $user=$this->lianKuArray($sql);
	    return $user;
	}
	private function addRewardMoney($user_id,$add_num,$reward_type)
	{
	    $bonus_id=$this->addMemberReward($user_id, $reward_type, $add_num);
	    if ($this->currency['1']['reward_ratio']>0) {
	        $this->incMemberMoneyByMemberIdAndMoneyId($user_id, 1, $add_num*$this->currency['1']['reward_ratio']);
	        $this->addFinance($user_id, $reward_type, $add_num*$this->currency['1']['reward_ratio'], 1, $user_id, $bonus_id);
	    }
	    if ($this->currency['2']['reward_ratio']>0) {
	        $this->incMemberMoneyByMemberIdAndMoneyId($user_id, 2, $add_num*$this->currency['2']['reward_ratio']);
	        $this->addFinance($user_id, $reward_type, $add_num*$this->currency['2']['reward_ratio'], 2, $user_id, $bonus_id);
	    }
	    if ($this->currency['6']['reward_ratio']>0) {
	        $this->incMemberMoneyByMemberIdAndMoneyId($user_id, 6, $add_num*$this->currency['6']['reward_ratio']);
	        $this->addFinance($user_id, $reward_type, $add_num*$this->currency['6']['reward_ratio'], 6,$user_id, $bonus_id);
	    }
	    if ($this->currency['3']['reward_ratio']>0&&$reward_type!='2') {
	        $this->incMemberMoneyByMemberIdAndMoneyId($user_id, 3, $add_num*$this->currency['3']['reward_ratio']);
	    }
	}
	private function getBeTuiUserByUser($user_id)
	{
		$sql="select * from ".$this->mysql_prefix."user where tui_id = ".$user_id;
		$member=$this->lianKu($sql);
		return $member;
	}

	private function getJingtaiPowerMoney(){
// 	    $suffix=$this->checkSuffix();
	    $suffix='';
	    $money_id=5;
	    $sql="select * from ".$this->mysql_prefix."user_money".$suffix." where currency_id=".$money_id." and num>0";
	    $member_money=$this->lianKuArray($sql);
	    return $member_money;
	}
	//================================获取用户基本信息==============================#
	private function getUserByUserId($user_id){
		$sql="select * from ".$this->mysql_prefix."user where id = ".$user_id;
		$member=$this->lianKu($sql);
		return $member;
	}
	//==============================================================================#
	//================================获取用户基本信息==============================#
	private function getDownUserByUpId($user_id){
		$sql="select * from ".$this->mysql_prefix."user where jie_id = ".$user_id;
		$member=$this->lianKuArray($sql);
		return $member;
	}
	private function getLeavelInfoByLeavel($leavel)
	{
	    $sql="select * from ".$this->mysql_prefix."leavel where id=".$leavel;
	    $leavel=$this->lianKu($sql);
	    return $leavel;
	}
	private function incUserYeji($parent_all)
    {
        foreach ($parent_all as $k=>$parent)
        {
			$this->incMemberYejiByMemberId($parent['id'],10000,'all_');
        }
    }
	
	
	//====================================用户加钱==================================#
	private function incMemberMoneyByMemberIdAndMoneyId($member_id,$money_id,$num){
		$suffix=$this->checkSuffix($member_id);
		$sql="select * from ".$this->mysql_prefix."user_money".$suffix." where currency_id=".$money_id." and user_id=".$member_id;
		// echo $sql;die;
		$member_money=$this->lianKu($sql);
		if(!$member_money){
			$sql="INSERT INTO ".$this->mysql_prefix."user_money".$suffix."(user_id,currency_id,num) VALUES (".$member_id.",'".$money_id."',0)";
			$member_money['id']=$this->insertCarry($sql);
		}
		$sql="update ".$this->mysql_prefix."user_money".$suffix." set num=num+".$num." where id=".$member_money['id'];
		$this->sqlCarry($sql);
	}
	private function decMemberMoneyByMemberIdAndMoneyId($member_id,$money_id,$num){
		$suffix=$this->checkSuffix($member_id);
		$sql="select * from ".$this->mysql_prefix."user_money".$suffix." where currency_id=".$money_id." and user_id=".$member_id;
		$member_money=$this->lianKu($sql);
		if(!$member_money){
			$sql="INSERT INTO ".$this->mysql_prefix."user_money".$suffix."(user_id,currency_id,num) VALUES (".$member_id.",'".$money_id."',0)";
			$member_money['id']=$this->insertCarry($sql);return;
		}
		$sql="update ".$this->mysql_prefix."user_money".$suffix." set num=num-".$num." where id=".$member_money['id'];
		$this->sqlCarry($sql);
	}
	private function incMemberYejiByMemberId($member_id,$num,$quyu=''){
		$suffix=$this->checkSuffix($member_id);
		$sql="update ".$this->mysql_prefix."user".$suffix." set ".$quyu."yeji=".$quyu."yeji+".$num."  where member_id=".$member_id;
		$this->sqlCarry($sql);
	}
	private function getMemberMoneyByMemberIdAndMoneyId($member_id,$money_id){
		$suffix=$this->checkSuffix($member_id);
		$sql="select * from ".$this->mysql_prefix."user_money".$suffix." where currency_id=".$money_id." and user_id=".$member_id;
		$member_money=$this->lianKu($sql);
		if(!$member_money){
			$sql="INSERT INTO ".$this->mysql_prefix."user_money".$suffix."(user_id,currency_id,num) VALUES (".$member_id.",'".$money_id."',0)";
			$member_money['id']=$this->insertCarry($sql);
			$sql="select * from ".$this->mysql_prefix."user_money".$suffix." where id=".$member_money['id'];
			return $this->lianKu($sql);
		}
		return $member_money;
	}
	private function getMemberLeavelByMemberMoney($num){
		$sql="select * from ".$this->mysql_prefix."leavel where small_num<=".$num." and big_num>=".$num;
		return $this->lianKu($sql);
	}
	//==============================================================================#
	//====================================分表方法==================================#
	private function checkSuffix($id,$n=''){
		if($n)
		{
			return $id%$n;
		}
		return '';
	}
	//==============================================================================#
	//================================获取大区用户==================================#
	public function daqu($member,$num){
		$user=$this->getParentByChildrenAxes($member['x_axes'],$member['y_axes'],$num);
		if(empty($user)){
			return ;
		}
		return $user;
	}
	private function getParentByChildren($jie,$num=9999999999){
		$num=(int)$num;
		// $n=$jie;
		$user_all=[];
		while($jie&&$num>0){
			$sql="select * from ".$this->mysql_prefix."user where id=".$jie;
			$user=$this->lianKu($sql);
		    $jie=$user['jie_id'];
		    if ($user) {
		         $user_all[]=$user;
		    }
		    $num--;
		} 
		// var_dump($parent);die();
		return $user_all;
		
	}
	//==============================================================================#
	//================================修正对碰奖奖金================================#
	private function checkDuipengMoney($member_id,$num,$leavel){
		$money=$this->automatic_config['dongmax'.$leavel];
		$duipeng_num=min($num,$money);
		if($duipeng_num<0){
			$duipeng_num=0;
		}
		 return $duipeng_num;
	}
	//==============================================================================#
	//================================修正见点奖奖金================================#
	private function checkjiandianMoney($member,$num){
		$money=$this->automatic_config['jiandianmax'.$member['leavel']];
		$new_num=min($num,$money-$member['get_jiandian_num']);
		if($new_num<0){
			$new_num=0;
		}
		 return $new_num;
	}
	//==============================================================================#
	//================================获取用户基本信息==============================#
	private function getMemberByMemberId($member_id){
		$sql="select * from ".$this->mysql_prefix."user where id = ".$member_id;
		$member=$this->lianKu($sql);
		return $member;
	}
	//==============================================================================#
	//=====================================自动程序配置=============================#
	private function getRewardConfig(){
		$sql="select * from ".$this->mysql_prefix."reward_config";
		$sys=$this->lianKuArray($sql);
		foreach($sys as $k=>$v){
			$config[$v['key']]=$v['value'];
		}
		return $config;
	}
	//=====================================奖金统计插入=============================#
	protected function addMemberReward($user_id,$reward_type,$money){
		$sql="select * from ".$this->mysql_prefix."bonus_log".$this->checkSuffix($user_id)." where add_time='".strtotime(date('Y-m-d'))."'"." and user_id=".$user_id;
		$reward=$this->lianKu($sql);
		if(!$reward){		
			$sql="insert into ".$this->mysql_prefix."bonus_log".$this->checkSuffix($user_id)." (user_id,add_time) values('".$user_id."','".strtotime(date('Y-m-d'))."')";		
			$reward['id']=$this->insertCarry($sql);
		}
		// $type=$this->checkRewardFieldByFinanceType($finance_type);
		$sql="update ".$this->mysql_prefix."bonus_log".$this->checkSuffix($user_id)." set bonus".$reward_type."=bonus".$reward_type."+".$money." where id=".$reward['id'];
		$this->sqlCarry($sql);
		
		return $reward['id'];
	}
	private function checkRewardFieldByFinanceType($finance_type){
		switch ($finance_type) {
			case 114:
			$type='jiandian';
			break;
			case 115:
			$type='duipeng';
			break;
			case 116:
			$type='tuijian';
			break;
			case 117:
			$type='jicha';
			break;
			case 113:
			$type='jihuo';
			break;
			case 69:
			$type='jingtai_jiandian';
			break;
			case 68:
			$type='tuijian';
			break;
			case 70:
			$type='jingtai';
			break;
			default:$type='error';break;			
		}
		return $type;
	}
	//==============================================================================#
	//=====================================静态奖金添加=============================#
	private function addJingtaimoney($mills_id,$num,$member_id){
		$sql="UPDATE ".$this->mysql_prefix."mills SET back_money=back_money+".$num." WHERE  mills_id=".$mills_id;
		$this->sqlCarry($sql);
		$sql="insert into ".$this->mysql_prefix."member_jingtai".$this->checkSuffix($member_id)."(member_id,num,add_time,mills_id) values('".$member_id."','".$num."','".time()."','".$mills_id."')";
		$this->sqlCarry($sql);	
	}
	//==============================================================================#
	//=====================================日志插入方法=============================#
	private function addFinance($user_id,$type,$num,$money_id,$from_id,$bonus_id){
		$sql="INSERT INTO ".$this->mysql_prefix."finance_log".$this->checkSuffix($user_id)."(user_id,type,num,add_time,currency_id,from_id,bonus_id) VALUES (".$user_id.",'".$type."',".$num.",".time().",".$money_id.",".$from_id.",".$bonus_id.")";
		echo $sql;
		$this->sqlCarry($sql);
	}
	//==============================================================================#
	//=====================================查询推荐上线方法=========================#
	private function getUpUserByTuijianid($tuijianid,$num=2,$k=0){
		$user[]=$this->getMemberByMemberId($tuijianid);
		for($i=1;$i<$num;$i++){
			if(empty($user[$i-1]['tuijianid'])){
				return $user;
			}
			$user[]=$this->getMemberByMemberId($user[$i-1]['tuijianid']);
		}
		return $user;
	}
	//==============================================================================#
	//=======================================执行方法===============================#
	private function sqlCarry($sql){
		$link= mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pwd) or die("数据库连接失败");
		mysql_select_db($this->mysql_db,$link);
		mysql_set_charset("utf8");
		$result=mysql_query($sql,$link);
	}
	//==============================================================================#
	//=======================================插入方法===============================#
	private function insertCarry($sql){
		$link= mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pwd) or die("数据库连接失败");
		mysql_select_db($this->mysql_db,$link);
		mysql_set_charset("utf8");
		$result=mysql_query($sql,$link);
		return mysql_insert_id();
	}
	//==============================================================================#
	//=================================查单条数据方法===============================#
	private function lianKu($sql){
		$link= mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pwd) or die("数据库连接失败");
		mysql_select_db($this->mysql_db,$link);
		mysql_set_charset("utf8");
		$result=mysql_query($sql,$link);
		$user=mysql_fetch_assoc($result);
		mysql_free_result($result);
		return $user;
	}
	//==============================================================================#
	//=================================查多条数据方法===============================#
	private function lianKuArray($sql){
		$res="";
		$link= mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pwd) or die("数据库连接失败");
		mysql_select_db($this->mysql_db,$link);
		mysql_set_charset("utf8");
		$result=mysql_query($sql,$link);
		while($user=mysql_fetch_assoc($result)){
			$res[]=$user;
		}
		mysql_free_result($result);
		return $res;
	}
	//==============================================================================#
}
	$zidong=new zidong();
	$zidong->jingtai();
	$zidong->duipeng();
	mysql_close();
?>